package service
{
	import domain.Project;
	
	import mx.collections.ArrayCollection;
	
	public class GetLatestBuildResultsRequest {
		private var responseCallback:Function;
		private var bambooService:BambooService;
		
		private var work:int;
    	private var projects:ArrayCollection;

		private var username:String;
		private var password:String;
		
		private var auth:String;
		
		public function GetLatestBuildResultsRequest( username:String, password:String, projects:ArrayCollection, bambooService:BambooService, responseCallback:Function=null) {
			this.username = username;
			this.password = password;
			this.projects = projects;
			this.responseCallback = responseCallback;
			this.bambooService = bambooService;
		}
		
		public function send():void {
			if( projects.length == 0 ){
				trace("nothing to load");
				onExecuteSuccess();
			} else {
				bambooService.requestAuthToken( username, password, onRequestAuthTokenSuccess );
			}
		}
		
		private function onRequestAuthTokenSuccess(auth:String):void { 
			this.auth = auth;
			trace("requesting latest build results...");
			work = projects.length;

			for each( var project:Project in projects ){
				bambooService.loadLatestProjectResults(auth, project, onLoadLatestProjectResults);
			}
		} 

		private function onLoadLatestProjectResults( project:Project ):void {
			trace("recieved latest build results for project["+project.key+"]");
			work--;
			if( work == 0 ){
				bambooService.releaseAuthToken( auth, onExecuteSuccess );
			}
		}
		
		private function onExecuteSuccess():void {
			if( responseCallback != null ){
				responseCallback();
			}
		}
		
	}
}